<template>
  <div id="menuBox">
    <el-switch v-model="draggable" active-text="开启拖拽" inactive-text="禁止拖拽"></el-switch>
    &nbsp;&nbsp;&nbsp;
    <el-button type="primary" @click="batchSave" round size="mini" v-if="draggable">批量保存</el-button>
    <el-button type="danger" @click="batchDelete" round size="mini" >批量删除</el-button>
    <hr />
    <el-tree
      :data="menus"
      :props="defaultProps"
      show-checkbox
      :expand-on-click-node="false"
      node-key="catId"
      :default-expanded-keys="expandedKeys"
      @node-drop="handleDrop"
      :draggable="draggable"
      :allow-drop="allowDrop"
      ref="menuTree"
    >
      <!-- @node-drop="handDrop" 拖拽成功 -->
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button v-if="node.level <= 2" type="text" size="mini" @click="() => append(data)">添加</el-button>
          <el-button type="text" size="mini" @click="() => edit(node, data)">编辑</el-button>
          <el-button v-if="node.childNodes.length == 0" type="text" size="mini" @click="() => remove(node, data)">删除</el-button>
        </span>
      </span>
    </el-tree>
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%">
      <el-form :model="category">
        <el-form-item label="分类名称"><el-input v-model="category.name" autocomplete="off"></el-input></el-form-item>
        <el-form-item label="图标"><el-input v-model="category.icon" autocomplete="off"></el-input></el-form-item>
        <el-form-item label="计量单位"><el-input v-model="category.productUnit" autocomplete="off"></el-input></el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitData">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: '',
  components: {},
  props: {},

  data() {
    return {
      category: { name: '', parentCid: 0, catLevel: 0, showStatus: 1, sort: 0, catId: null, icon: '', productUnit: '' },
      menus: [],
      expandedKeys: [], // expandedKeys默认展开的数组
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      dialogVisible: false,
      dialogType: '', //edit, add
      dialogTitle: '',
      maxLevel: 0, //拖拽的最大层级
      updateNodes: [],
      draggable: false, //是否可拖拽
      parentCids: []
    };
  },
  created() {
    this.getMenus();
  },
  methods: {
    //保存数据
    submitData() {
      if (this.dialogType == 'add') {
        this.addCategory();
      } else if (this.dialogType == 'edit') {
        this.editCategory();
      }
    },
    //修改数据
    editCategory() {
      //只编辑部分数据
      // let {catId, name, icon, productUnit} = this.category;
      this.dataListLoading = true;
      this.$http({
        url: this.$http.adornUrl('/product/category/update'),
        method: 'post',
        // data: this.$http.adornData({catId, name, icon, productUnit}, false)
        data: this.$http.adornData(this.category, false)
      }).then(({ data }) => {
        this.dialogVisible = false;
        this.$message({
          message: '操作成功',
          type: 'success',
          duration: 1500,
          onClose: () => {
            this.getMenus();
            this.expandedKeys = [this.category.parentCid];
            this.dataListLoading = false;
          }
        });
      });
    },
    //添加数据
    addCategory() {
      this.dataListLoading = true;
      this.$http({
        url: this.$http.adornUrl('/product/category/save'),
        method: 'post',
        data: this.$http.adornData(this.category, false)
      }).then(({ data }) => {
        this.dialogVisible = false;
        this.$message({
          message: '操作成功',
          type: 'success',
          duration: 1500,
          onClose: () => {
            this.getMenus();
            this.expandedKeys = [this.category.parentCid];
            this.dataListLoading = false;
          }
        });
      });
    },
    getMenus() {
      this.dataListLoading = true;
      this.$http({
        url: this.$http.adornUrl('/product/category/list/tree'),
        method: 'get'
      }).then(({ data }) => {
        console.log('data==', data);
        if (data && data.code === 0) {
          this.menus = data.data;
        } else {
        }
        this.dataListLoading = false;
      });
    },
    append(data) {
      this.dialogType = 'add';
      this.dialogTitle = '添加分类';
      this.dialogVisible = true;

      this.category.parentCid = data.catId;
      this.category.catLevel = data.catLevel * 1 + 1;

      this.category.name = '';
      this.category.sort = 0;
      this.category.catId = null;
      this.category.icon = '';
      this.category.showStatus = 1;
      this.category.productUnit = '';
    },
    edit(node, data) {
      this.dialogType = 'edit';
      this.dialogTitle = '修改分类';
      this.dialogVisible = true;
      //发送请求，获取最新的数据
      this.dataListLoading = true;
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: 'get'
      }).then(({ data }) => {
        console.log('data==', data);
        // let obj = data.data;
        // this.category.name = obj.name;
        // this.category.catId = obj.catId;
        // this.category.icon = obj.icon;
        // this.category.productUnit = obj.productUnit;
        // this.category.parentCid = obj.parentCid;
        this.category = data.data;
        this.dataListLoading = false;
      });
      // this.category.name = data.name;
      // this.category.catId = data.catId;
    },
    remove(node, data) {
      console.log('remove node=', node);
      var ids = [data.catId];
      this.$confirm(`此操作将永久删除菜单【${data.name}】, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl('/product/category/delete'),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({ data }) => {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getMenus();
                console.log('remove expandedKeys=', node.parent.data.catId);
                this.expandedKeys = [node.parent.data.catId];
              }
            });
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    allowDrop(draggingNode, dropNode, type) {
      //1、被拖动的节点以及所在的父节点总层数不能大于3
      this.countNodeLevel(draggingNode);
      //当前节点的深度
      console.log('this.maxLevel===', this.maxLevel);
      console.log('draggingNode.level===', draggingNode.level);
      let deep = Math.abs(this.maxLevel - draggingNode.level) + 1;
      console.log('deep===', deep);
      if (type == 'inner') {
        //拖动到另一个节点内部
        return deep + dropNode.level <= 3;
      } else {
        //拖动到另一个节点内部
        return deep + dropNode.parent.level <= 3;
      }
    },
    //得到节点最深层级
    countNodeLevel(node) {
      //console.log("node===",node)
      //找到所有子节点，求出最大深度
      let childNodes = node.childNodes
      if (childNodes != null && childNodes.length > 0) {
        for (let i = 0; i < childNodes.length; i++) {
          if (childNodes[i].level > this.maxLevel) {
            this.maxLevel = childNodes[i].level;
          }
          this.countNodeLevel(childNodes[i]);
        }
      } else {
        this.maxLevel = node.level;
      }
    },
    //拖拽成功
    handleDrop(draggingNode, dropNode, dropType, ev) {
      //1、获取当前节点的父节点Id
      let parentCid = 0;
      let siblings = null;
      if (dropType == 'inner') {
        parentCid = dropNode.data.catId ? dropNode.data.catId : 0;
        siblings = dropNode.childNodes;
      } else {
        //如果是 'before' 或 'after'
        parentCid = dropNode.parent.data.catId ? dropNode.parent.data.catId : 0;
        siblings = dropNode.parent.childNodes;
      }
      this.parentCids.push(parentCid);
      console.log('siblings==', siblings);
      //2.当前拖拽节点的最新排序
      for (let i = 0; i < siblings.length; i++) {
        if (siblings[i].data.catId == draggingNode.data.catId) {
          //层级
          let catLevel = draggingNode.level;
          if (siblings[i].level != draggingNode.level) {
            //说明层级变化了，在dropNode内部，则层级 + 1
            catLevel = siblings[i].level;
            //更新当前节点的level
            this.updateChildNodeLevel(siblings[i]);
          }
          //如果是拖拽节点，要修改parentCid
          this.updateNodes.push({ catId: siblings[i].data.catId, sort: i, parentCid: parentCid, catLevel: catLevel });
        } else {
          //其它节点只要修改sort排序
          this.updateNodes.push({ catId: siblings[i].data.catId, sort: i });
        }
      }
      //3.当前拖拽节点的最新层级，后面内容保存到了batchSave方法中
      console.log('this.updateNodes==', this.updateNodes);
      // this.$http({
      //   url: this.$http.adornUrl('/product/category/update/sort'),
      //   method: 'post',
      //   data: this.$http.adornData(this.updateNodes, false)
      // }).then(({ data }) => {
      //   this.$message({
      //     message: '操作成功',
      //     type: 'success',
      //     duration: 1500,
      //     onClose: () => {
      //       this.getMenus();
      //       console.log('handleDrop expandedKeys=', parentCid);
      //       this.expandedKeys = [parentCid];
      //       //清空数据
      //       this.updateNodes = [];
      //       this.maxLevel = 0;
      //     }
      //   });
      // });
    },
    //批量保存拖拽后的菜单数据
    batchSave() {
      this.$http({
        url: this.$http.adornUrl('/product/category/update/sort'),
        method: 'post',
        data: this.$http.adornData(this.updateNodes, false)
      }).then(({ data }) => {
        this.$message({
          message: '操作成功',
          type: 'success',
          duration: 1500,
          onClose: () => {
            this.getMenus();
            this.expandedKeys = this.parentCids;
            //清空数据
            this.updateNodes = [];
            this.maxLevel = 0;
            this.parentCids = [];
          }
        });
      });
    },
    //更新当前节点所有node的level
    updateChildNodeLevel(node) {
      console.log('updateChildNodeLevel node==', node);
      if (node.childNodes != null && node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          let cNode = node.childNodes[i];
          let data = cNode.data;
          this.updateNodes.push({ catId: data.catId, catLevel: cNode.level });
          //更新子节点的level
          this.updateChildNodeLevel(cNode);
        }
      }
    },
    //批量删除节点
    batchDelete(){
      //选中的节点
      let checkedNodes = this.$refs.menuTree.getCheckedNodes(false, false)
      let catIds = []
      if(checkedNodes.length > 0){
        for(let i = 0; i < checkedNodes.length; i++){
          catIds.push(checkedNodes[i].catId)
        }
        this.$confirm(`您确定要删除这些菜单吗, 是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.$http({
              url: this.$http.adornUrl('/product/category/delete'),
              method: 'post',
              data: this.$http.adornData(catIds, false)
            }).then(({ data }) => {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getMenus();
                  // console.log('remove expandedKeys=', node.parent.data.catId);
                  // this.expandedKeys = [node.parent.data.catId];
                }
              });
            });
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          });

      }

    }

  },
  computed: {},
  watch: {},
  mounted() {},
  activated() {}
};
</script>

<style scoped lang="scss"></style>
